package com.pengheng.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;


/**
 * @author pengheng
 * @date 2024年8月8日17:26:39
 */
@Slf4j
public class ServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("连接客户端" + ctx.channel().remoteAddress());
        Channel channel = ctx.channel();
//        ChannelHandler.channels.add(channel);
        ChannelHandler.channels.put(ctx.channel().id().toString(), channel);
        ctx.writeAndFlush(ctx.channel().id());

    }

    /**
     * 接受数据处理
     *
     * @param ctx
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("Server received: " + msg);
    }

    /**
     * 出现异常：
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("netty连接异常", cause);
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("断开客户端");
        ChannelHandler.channels.remove(ctx.channel().remoteAddress().toString());
    }

}